package com.qms.repast.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.qms.repast.R;
import com.qms.repast.entity.resbean.CityBean.BodyBean;

import java.util.List;

/**
 * @author 泅渡者
 * @date 2018/9/15 0015
 * @describe: 城市选择适配器
 */
public class CityListAdapter extends BaseAdapter implements SectionIndexer {
	private List<BodyBean> list = null;
	private Context mContext;

	public CityListAdapter (Context mContext, List<BodyBean> sourceDateList) {
		this.mContext = mContext;
		this.list = sourceDateList;
	}

	/**
	 * 当ListView数据发生变化时,调用此方法来更新ListView
	 *
	 * @param list
	 */
	public void updateListView (List<BodyBean>  list) {
		this.list = list;
		notifyDataSetChanged();
	}

	/**
	 * 获取适配器中的数据
	 *
	 * @return
	 */
	public BodyBean getCurrentItem (int i) {
		return this.list.get(i);
	}

	@Override
	public int getCount () {
		return this.list.size();
	}

	@Override
	public Object getItem (int position) {
		return list.get(position);
	}

	@Override
	public long getItemId (int position) {
		return position;
	}

	@Override
	public View getView (final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder;
		BodyBean mContent = list.get(position);
		if (view == null) {
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.layout_select_city, null);
			viewHolder.tvTitle = view.findViewById(R.id.tv_city_name);
			view.setTag(viewHolder);
			viewHolder.tvLetter = view.findViewById(R.id.tv_catagory);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}

		int section = getSectionForPosition(position);

		if (position == getPositionForSection(section)) {
			viewHolder.tvLetter.setVisibility(View.VISIBLE);
			viewHolder.tvLetter.setText(mContent.getLetter());
		} else {
			viewHolder.tvLetter.setVisibility(View.GONE);
		}

		viewHolder.tvTitle.setText(this.list.get(position).getCity());
		return view;

	}

	final static class ViewHolder {
		TextView tvLetter;
		TextView tvTitle;
	}

	@Override
	public int getSectionForPosition (int position) {
		return list.get(position).getLetter().charAt(0);
	}

	@Override
	public int getPositionForSection (int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getLetter();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public Object[] getSections () {
		return null;
	}
}
